import 'dart:io';

import 'package:ceramics/extensions/ab_widget_extensions.dart';
import 'package:ceramics/model/ab_singleton.dart';
import 'package:ceramics/styles/ab_styles.dart';
import 'package:ceramics/util/ab_api.dart';
import 'package:ceramics/util/ab_init_db.dart';
import 'package:ceramics/util/ab_loading.dart';
import 'package:ceramics/util/ab_log_util.dart';
import 'package:ceramics/util/ab_selector.dart';
import 'package:ceramics/util/empty.dart';
import 'package:ceramics/util/image_picker.dart';
import 'package:ceramics/widgets/ab_elevate_button.dart';
import 'package:ceramics/widgets/ab_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'ab_mine_page.dart';

class ABSettingProfilePage extends StatefulWidget {
  const ABSettingProfilePage({super.key});

  @override
  State<ABSettingProfilePage> createState() => _ABSettingProfilePageState();
}

class _ABSettingProfilePageState extends State<ABSettingProfilePage> {
  final _nameController = TextEditingController(text: ABSingleton.user?.nickname);
  String? _selectedImage;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        title: const Text('Profile'),
      ),
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage("images/login_bg.webp"),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              20.toVerticalBox,
              if (_selectedImage != null) 
                ClipRRect(
                    borderRadius: BorderRadius.circular(50),
                    child: Image.file(File(_selectedImage!), width: 100, height: 100,fit: BoxFit.cover).onTap(_changeAvatar))
              else
                ABCircleAvatar(url: ABSingleton.user?.avatar, size: 100).onTap(_changeAvatar),
              40.toVerticalBox,
              _buildNickName(),
              20.toVerticalBox,
              _buildBirthDay(),
              20.toVerticalBox,
              _buildCountry(),
              100.toVerticalBox,
              ABElevateButton(child: const Text('Submit',style: ABStyles.tsWhite20R), onPressed: (){
                _submit();
              }).size(width: 200)
            ],
          ).padSymmetric(vertical: 20, horizontal: 20),
        ),
      ).onTap(() => FocusScope.of(context).unfocus())
    );
  }

  _changeAvatar() async {
    var image = await selectPhoto(context);
    if (isNullOrEmpty(image)) return;
    _selectedImage = image;
    LogPvManger.stat(page: 'editavatar');
    setState(() {});
  }

  _submit() async {
    if (!isNullOrEmpty(_selectedImage)) {
      await api.updateAvatar(_selectedImage!);
    }
    if (!isNullOrEmpty(_nameController.text)) {
      toast('Please input your nickname'.tr);
    }
    await api.saveUserInfo(nickname: _nameController.text, country: ABSingleton.user?.country, birthday: ABSingleton.user?.birthday);
    await replaceTableUser();
    Get.find<ABMineController>().update();
    Get.back();
    Future.delayed(const Duration(milliseconds: 1300), () {
      toast('Submit successfully'.tr);
    });
  }

  Widget _buildNickName() {
    return Container(
      decoration: const BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(20)),
        border: Border.fromBorderSide(BorderSide(color: ABStyles.normalBlack)),
      ),
      child: Row(
        children: [
          10.toHorizontalBox,
          Text('Nickname'.tr, style: ABStyles.tsDarkBlack17Bold),
          const Spacer(),
          Text(ABSingleton.user?.nickname ?? '', style: ABStyles.tsLightBlack15),
          10.toHorizontalBox,
        ],
      ).padSymmetric(vertical: 8, horizontal: 20),
    ).onTap(() {
      showCupertinoDialog(context: context, builder: (context)
      {
        return CupertinoAlertDialog(
          title: const Text('Change Nickname').padOnly(bottom: 20),
          content: CupertinoTextField(
            controller: _nameController,
            placeholder: 'Please input your nickname',
          ),
          actions: [
            CupertinoDialogAction(
              child: const Text('Cancel'),
              onPressed: () {
                Get.back();
              },
            ),
            CupertinoDialogAction(
              child: const Text('Confirm'),
              onPressed: () {
                Get.back();
                setState(() {
                  ABSingleton.user?.nickname = _nameController.text;
                });
              },
            )
          ],
        );
      });
    });
  }

  Widget _buildCountry() {
      return Container(
      decoration: const BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(20)),
        border: Border.fromBorderSide(BorderSide(color: ABStyles.normalBlack)),
      ),
      child: Row(
        children: [
          10.toHorizontalBox,
          Text('Country'.tr, style: ABStyles.tsDarkBlack17Bold),
          const Spacer(),
          Text(ABSingleton.user?.country ?? '', style: ABStyles.tsLightBlack15),
          10.toHorizontalBox,
        ],
      ).padSymmetric(vertical: 8, horizontal: 20),
    ).onTap(() {
      var countries = ['USA', 'UK', 'Japan', 'Korea', 'France', 'Germany', 'Italy', 'Spain', 'Canada', 'Australia', 'Brazil', 'Russia', 'India', 'Mexico', 'Indonesia', 'Turkey', 'Netherlands', 'Saudi Arabia', 'Switzerland', 'Sweden', 'Poland', 'Belgium', 'Norway', 'Denmark', 'Finland', 'Austria', 'Greece', 'Portugal', 'Ireland', 'Czech Republic', 'Romania', 'Hungary', 'Ukraine', 'Croatia', 'Bulgaria', 'Slovakia', 'Slovenia', 'Lithuania', 'Latvia', 'Estonia', 'Cyprus', 'Malta', 'Luxembourg', 'Iceland', 'Liechtenstein', 'Monaco', 'San Marino', 'Vatican City'];

      // use picker view
      showPickerView(
          initialIndex: countries.indexOf(ABSingleton.user?.country ?? 'USA'),
          context: context, items: countries, onSelected: (index) {
        setState(() {
          ABSingleton.user?.country = countries[index];
        });
      });
    });
  }

  Widget _buildBirthDay() {
    return Container(
      decoration: const BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(20)),
        border: Border.fromBorderSide(BorderSide(color: ABStyles.normalBlack)),
      ),
      child: Row(
        children: [
          10.toHorizontalBox,
          Text('Birthday'.tr, style: ABStyles.tsDarkBlack17Bold),
          const Spacer(),
          Text(ABSingleton.user?.birthday ?? '', style: ABStyles.tsLightBlack15),
          10.toHorizontalBox,
        ],
      ).padSymmetric(vertical: 8, horizontal: 20),
    ).onTap(() {
      DateTime myDate = DateTime.parse(ABSingleton.user?.birthday ?? DateTime.now().toString().substring(0, 10));
      // 18年前, 60年前
      DateTime minDate = DateTime.now().subtract( const Duration(days: 365 * 18 + (18 ~/ 4) + 1));
      DateTime maxDate = DateTime.now().subtract(const Duration(days: 365 * 80));
      showDatePicker(
        context: context,
        initialDate: myDate,
        firstDate: maxDate,
        lastDate: minDate,
      ).then((value) {
        if (value != null) {
          ABSingleton.user?.birthday = value.toString().substring(0, 10);
          setState(() {});
        }});
      });
  }
}
